<template>
  <view class="login page custom-page">
    <view class="top">
      <image class="img" src="../../static/img/logo.png" />
    </view>

    <view v-if="showModify" class="forget">若您忘记了密码，可在此重新设置新密码。</view>

    <u-form :model="form" ref="uForm" label-width="180">
      <u-form-item prop="name">
        <u-input v-model="form.name" placeholder="手机号" maxlength="11" /> 
      </u-form-item>

      <u-form-item prop="code">
        <u-input  v-model="form.code" placeholder="验证码" />
        <u-button shape="circle" :disabled="showBtn" class="dis_btn" @click="handleCaptcha">{{buttonText}}</u-button>
      </u-form-item>

      <u-form-item prop="password">
        <u-input type="password" v-model="form.password" placeholder="登陆密码" />
      </u-form-item>
    </u-form>

    <view class="btn">
      <u-button class="login_btn" ripple  shape="circle" :loading="loading" @click="handleRegister"
      > {{ showModify ? '修改密码' : '注册并登录' }} </u-button>

      <view v-if="!showModify" class="agree">
        <u-checkbox 
          v-model="showAgree"
          shape="circle" 
          class="text_color"
        >同意</u-checkbox>
        <view class="text_color">《软件用户协议》</view>
        <view class="text_color">《隐私政策》</view>
      </view>
    </view>

  </view>
</template>

<script>
import { login, getUser } from '../../api/modules/user'
import { toPage } from '../../utils'
import {  getCode, updateResetPassword, registPassword } from '../../api/modules/user';
import md5 from 'md5';

export default {
  data() {
    return {
      form: {
        name: '18112918611',
        password: 'qwerty1',
        // password: '',
        code: '888666',
      },
      rules: {
        name: [
					{
						required: true,
						message: '请输入手机号码',
						// 可以单个或者同时写两个触发验证方式
						trigger: 'blur,change'
					},{
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              // 上面有说，返回true表示校验通过，返回false表示不通过
              // this.$u.test.mobile()就是返回true或者false的
              return this.$u.test.mobile(value);
            },
            message: '手机号码不正确',
            // 触发器可以同时用blur和change
            trigger: ['change','blur'],
          }
				],
        code: [
        {
						required: true,
						message: '请输入验证码',
						trigger: 'blur,change'
					}
        ],
        password: [
        {
						required: true,
						message: '请输入密码',
						trigger: 'blur,change'
					}
        ],
      },
      loading: false,
      showAgree: false,  // 是否同意
      showModify: false, // 修改密码 ----
      showBtn: false, // // 是否禁用按钮 code
      countdown: 60, // 秒钟
    }
  },
  mounted() {
    if(this.$route.query.type == 1) {
      this.showModify = false;
    } else {
      this.showModify = true;
    }
  },
  computed: {
    buttonText: function() {
      return this.showBtn ? `重新获取${this.countdown}` : "获取验证码";
    }
  },

  methods: {
    handleRegister() {
      this.$refs.uForm.validate(valid => {
				if (valid) {
          console.log('--', this.form)
          if (this.form.password.length < 6) {
            this.$u.toast('密码必须大于六位')
            return;
          }
          let data = {
            ...this.form,
            password: md5(this.form.password)
          }

          if (this.showModify) { // 修改密码
            updateResetPassword(data).then(res => {
              const { code, message } = res || {}
              if (code === 201) {
                this.$u.toast('密码修改成功')
                uni.navigateBack({
                  delta: 1,
                });
              }  else {
                this.$u.toast(`${message}`)
              }
            })
          } else {
            if (!this.showAgree) { // 注册页面
              this.$u.toast('请先阅读《软件用户协议》')
              return
            }

            registPassword(data).then(res => {
              const { code, message, data } = res || {}
              if (code === 201) {
                this.$u.toast('注册成功')
                console.log('res', res)
                uni.setStorage({
                  key: 'token',
                  data: data.token
                })
                getApp().globalData.token = data.token
                getApp().globalData.loginForm = this.form;
                getApp().globalData.glbCurrentDataMap = data
                uni.navigateTo({
                  url: '/pages/index/index' 
                })
              } else {
                this.$u.toast(`${message}`)
              }
            })

            console.log('------注册页面请求')
          }
				} else {
					console.log('验证失败++++');
				}
			});
      
      
      // console.log("注册账户---", this.form)
    },
    handleCaptcha() { // 获取验证码
      let reg_name = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (this.form.name === '') {
        this.$u.toast('请输入您的手机号码')
        return
      } else if (!reg_name.test(this.form.name)) {
        this.$u.toast('手机号不正确')
        return
      }
      if (this.showBtn) {
        return;
      }
      const { name } = this.form || {};
      let data = {
        phone: name,
        action: 'regist'
      }
      this._getCode(data)
      this.showBtn = true;
      this.countdown = 60;
      const times = setInterval(() => {
        this.countdown--;
        if (this.countdown === 0) {
          clearInterval(times);
          this.showBtn = false;
        }
      }, 1000)
      
    },
    handleLogin() {
      this.loading = true
      uni.removeStorageSync('token')
      let form = {
        name: this.form.name,
        password: md5(this.form.password)
      }
      console.log('加密', form)
      login(form).then((res) => {
        if (res.code === 200) {
          console.log(res.data)
          this.$u.toast('登录成功')
          uni.setStorage({
            key: 'token',
            data: res.data.token
          })
          getApp().globalData.token = res.data.token
          getApp().globalData.loginForm = this.form;
          getApp().globalData.glbCurrentDataMap = res.data
          uni.navigateTo({
            url: '/pages/index/index' 
          })
        } else {
          this.$u.toast(res.message)
        }
      })
    },
    _getCode(data) { // 获取验证码
      // //传phone，action:动作名称（eg:regist,login,reset_password)
      // 万能短信 888666
      getCode(data).then(res => {
        const { code, data } = res || {}
        if (code === 200) {
          this.$u.toast(`${data}`)
        }
      })
    },
  },
  // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	}
}
</script>

<style lang="scss" scoped>
.login {
  padding: 80rpx 60rpx;

  .top {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 40rpx;
    .img {
      width: 150rpx;
      height: 150rpx;
      border-radius: 50%;
    }
  }


  .dis_btn {
    color: #e9a058;
    border-radius: 30rpx !important;
    background-color: #f3f0ed;
  }

  .forget {
    color: #b9b9b9;
    margin-bottom: 30rpx;
  }

  .btn {
    .pass {
      display: flex;
      justify-content: end;
      color: #eab131;
    }
    .agree{
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 80rpx;
      color: #b9b9b9;
      /deep/ .u-checkbox__label {
        color: #b9b9b9;
      }

      .text_color {
        color: #b9b9b9;
      }

      
    }
    .login_btn {
        color: #FFFFFF;
        font-size: 34upx;
        width: 470upx;
        height: 100upx;
        background: linear-gradient(-90deg, rgba(63, 205, 235, 1), rgba(188, 226, 158, 1));
        box-shadow: 0upx 0upx 13upx 0upx rgba(164, 217, 228, 0.2);
        border-radius: 50upx;
        line-height: 100upx;
        text-align: center;
        margin-left: auto;
        margin-right: auto;
        margin-top: 40upx;
    }
    .register_btn {
      color: #FFFFFF;
      font-size: 34upx;
      width: 470upx;
      height: 100upx;
      background: linear-gradient(-90deg,#bbed0b,#8dc63f);
      box-shadow: 0upx 0upx 13upx 0upx rgba(164, 217, 228, 0.2);
      border-radius: 50upx;
      line-height: 100upx;
      text-align: center;
      margin-left: auto;
      margin-right: auto;
      margin-top: 30upx;
    }
    .login_btn::after,
    .register_btn::after {
      border: none;
    }
    .customer {
      margin-top: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24rpx;
      color: #bebebe;
    }
  }
 
}
</style>
